package cn.bj.yu.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 周宇
 * @create 2020-08-16 22:09
 */
public class CASDemo {

    static AtomicReference<Integer> atomicReference = new AtomicReference<>(100);

    //CAS compareAndSet:比较并交换！
    public static void main(String[] args) {
        new Thread(() -> {
            atomicReference.compareAndSet(100, 101);
            atomicReference.compareAndSet(101, 100);
        }, "T1").start();

        new Thread(() -> {
            try {
                //暂停一秒钟，保证上面线程先执行
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicReference.compareAndSet(100, 2020);//修改成功
            System.out.println(atomicReference.get());
        }, "T2").start();
    }
}